<template>
  <div class="user-manage-container">
    <el-card class="manage-card">
      <template #header>
        <span>用户综合管理</span>
      </template>

      <!-- 搜索区域 -->
      <div class="search-section">
        <el-form :inline="true" :model="searchForm" class="demo-form-inline">
          <el-form-item label="关键词">
            <el-input
              v-model="searchForm.search"
              placeholder="请输入用户ID、昵称或手机号"
              clearable
              @clear="handleReset"
            />
          </el-form-item>

          <el-form-item label="状态">
            <el-select v-model="searchForm.state" placeholder="请选择">
              <el-option label="全部" value="" />
              <el-option label="正常" value="1" />
              <el-option label="禁用" value="0" />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 用户列表区域 -->
      <div class="user-list-section">
        <h3>用户列表 (总数: {{ total }})</h3>

      <!-- 表格 -->
<el-table
  :data="userList"
  border
  style="width: 100%"
  v-loading="tableLoading"
  :row-style="{ height: '60px' }"
>
  <!-- 原有列 -->
  <el-table-column prop="buyerUserId" label="用户ID" width="200" />
  <el-table-column prop="name" label="昵称" width="180" />
  <el-table-column prop="phone" label="手机号" width="180" />
  <!-- <el-table-column prop="memberLevelName" label="会员等级" width="120" /> -->

  <!-- 新增字段列 -->
  <el-table-column prop="balance" label="可用余额" width="180">
    <template #default="{ row }">
      {{ Number(row.balance || 0).toFixed(2) }}
    </template>
  </el-table-column>

  <el-table-column prop="frozenBalance" label="冻结余额" width="200">
    <template #default="{ row }">
      {{ Number(row.frozenBalance || 0).toFixed(2) }}
    </template>
  </el-table-column>

  <!-- <el-table-column prop="payPasswordLockTime" label="支付密码锁定时间" width="180">
    <template #default="{ row }">
      {{ row.payPasswordLockTime || '-' }}
    </template>
  </el-table-column> -->

  <el-table-column prop="account" label="非靓号账号" width="180" />

  <el-table-column label="私聊状态" width="200">
    <template #default="{ row }">
      <el-tag :type="row.privateChat === 1 ? 'success' : 'danger'">
        {{ row.privateChaT === 1 ? '开启' : '禁用' }}
      </el-tag>
    </template>
  </el-table-column>

  <el-table-column label="群聊状态" width="200">
    <template #default="{ row }">
      <el-tag :type="row.groupChat === 1 ? 'success' : 'danger'">
        
        {{ row.groupChat === 1 ? '开启' : '禁用' }}
      </el-tag>
    </template>
  </el-table-column>

<el-table-column label="冻结状态" width="160">
  <template #default="{ row }">
    <el-tag :type="row.frozenBalance > 0 ? 'danger' : 'success'">
      {{ row.frozenBalance > 0 ? '已冻结' : '正常' }}
    </el-tag>
  </template>
</el-table-column>


<el-table-column label="用户状态" width="140">
  <template #default="{ row }">
    <el-tag :type="row.state === 1 ? 'success' : 'danger'">
      {{ row.state === 1 ? '启用' : '禁用' }}
    </el-tag>
  </template>
</el-table-column>


  <!-- 操作列 -->
 <el-table-column label="操作" width="200">
  <template #default="{ row }">
    <!-- 禁用/启用按钮（保留原有逻辑） -->
    <el-button
      size="small"
      type="danger"
      @click="handleBan(row)"
      v-if="row.state === 1"
    >
      禁用
    </el-button>
    <el-button
      size="small"
      type="warning"
      @click="handleUnban(row)"
      v-if="row.state === 0"
    >
      启用
    </el-button>

    <!-- 冻结/解冻钱包按钮（按 frozenBalance 判断） -->
    <el-button
      size="small"
      type="primary"
      @click="handleFreeze(row)"
      v-if="row.frozenBalance <= 0"
    >
      冻结钱包
    </el-button>
    <el-button
      size="small"
      type="info"
      @click="handleUnfreeze(row)"
      v-if="row.frozenBalance > 0"
    >
      解冻钱包
    </el-button>
  </template>
</el-table-column>
</el-table>

        <!-- 分页 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          class="pagination-wrapper"
        ></el-pagination>
      </div>

      <!-- 对话框：确认禁用/启用 -->
      <el-dialog v-model="banDialogVisible" title="确认操作" width="400px">
        <p>确定要将用户 <strong>{{ banUser.name }}</strong> 的账号状态设置为 <strong>{{ banAction }}</strong> 吗？</p>
        <template #footer>
          <el-button @click="banDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmBan">确定</el-button>
        </template>
      </el-dialog>

      <!-- 对话框：冻结钱包 -->
      <el-dialog v-model="freezeDialogVisible" title="冻结钱包" width="500px">
        <el-form :model="freezeForm" label-width="100px">
          <el-form-item label="冻结金额">
            <el-input-number
              v-model="freezeForm.amount"
              :min="0"
              :max="999999"
              controls-position="right"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="冻结时长">
            <el-select v-model="freezeForm.expireTimeOption" placeholder="请选择">
              <el-option label="1小时" value="1h" />
              <el-option label="1天" value="1d" />
              <el-option label="1周" value="1w" />
              <el-option label="1个月" value="1m" />
              <el-option label="1年" value="1y" />
            </el-select>
          </el-form-item>
          <el-form-item label="原因">
            <el-input
              v-model="freezeForm.reason"
              placeholder="请输入冻结原因"
              type="textarea"
              :rows="3"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="freezeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmFreeze">提交</el-button>
        </template>
      </el-dialog>

      <!-- 对话框：解冻钱包 -->
      <el-dialog v-model="unfreezeDialogVisible" title="解冻钱包" width="400px">
        <p>确定要解冻用户 <strong>{{ unfreezeUser.name }}</strong> 的钱包吗？</p>
        <template #footer>
          <el-button @click="unfreezeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmUnfreeze">确定</el-button>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'UserManage',
  data() {
    return {
      tableLoading: false,
      userList: [],
      total: 0,
      currentPage: 1,
      pageSize: 10,

      searchForm: {
        search: '',
        state: ''
      },

      // 禁用/启用相关
      banDialogVisible: false,
      banUser: null,
      banAction: '',

      // 冻结钱包相关
      freezeDialogVisible: false,
      freezeForm: {
        amount: 0,
        expireTimeOption: '1d',
        reason: ''
      },
      freezeTargetUser: null,

      // 解冻钱包相关
      unfreezeDialogVisible: false,
      unfreezeUser: null,
    }
  },

  methods: {
    // 加载用户列表
    async loadUserList() {
      this.tableLoading = true
      try {
        const response = await request({
          url: '/userManage/getUserList',
          method: 'get',
          params: {
            page: this.currentPage,
            pageSize: this.pageSize,
            search: this.searchForm.search,
            state: this.searchForm.state
          }
        })

        if (response.code === 200 || response.code === "200") {
          this.userList = response.data.list || []
          this.total = response.data.total || 0
        } else {
          this.$message.error(response.message || '加载失败')
        }
      } catch (error) {
        this.$message.error('请求失败：' + error.message)
      } finally {
        this.tableLoading = false
      }
    },

    // 搜索
    handleSearch() {
      this.currentPage = 1
      this.loadUserList()
    },

    // 重置
    handleReset() {
      this.searchForm.search = ''
      this.searchForm.state = ''
      this.currentPage = 1
      this.loadUserList()
    },

    // 分页
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.loadUserList()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.loadUserList()
    },

    // 禁用用户
    handleBan(user) {
      this.banUser = user
      this.banAction = '禁用'
      this.banDialogVisible = true
    },

    // 启用用户
    handleUnban(user) {
      this.banUser = user
      this.banAction = '启用'
      this.banDialogVisible = true
    },

    // 提交禁用/启用
    async confirmBan() {
      const params = {
        buyerUserId: this.banUser.buyerUserId,
        state: this.banAction === '禁用' ? 0 : 1
      }

      try {
        const response = await request({
          url: '/userManage/buyerUser/update',
          method: 'post',
          data: params
        })

        if (response.code === 200 || response.code === "200") {
          alert('操作成功')
          this.banDialogVisible = false
          this.loadUserList()
        } else {
         alert(response.message || '操作失败')
        }
      } catch (error) {
        alert('提交失败：' + error.message)
      }
    },

    // 冻结钱包
    handleFreeze(user) {
      this.freezeTargetUser = user
      this.freezeForm.amount = 0
      this.freezeForm.reason = ''
      this.freezeDialogVisible = true
    },

    // 计算截止时间戳
    calculateExpireTime(option) {
      const now = new Date()
      switch (option) {
        case '1h': return now.getTime() + 60 * 60 * 1000
        case '1d': return now.getTime() + 24 * 60 * 60 * 1000
        case '1w': return now.getTime() + 7 * 24 * 60 * 60 * 1000
        case '1m': return now.getTime() + 30 * 24 * 60 * 60 * 1000
        case '1y': return now.getTime() + 365 * 24 * 60 * 60 * 1000
        default: return null
      }
    },

    // 提交冻结
    async confirmFreeze() {
      if (!this.freezeTargetUser) return

      const expireTime = this.calculateExpireTime(this.freezeForm.expireTimeOption)

      const params = {
        buyerUserId: this.freezeTargetUser.buyerUserId,
        actionType: 2, // 2-冻结
        amount: this.freezeForm.amount,
        expireTime: expireTime,
        reason: this.freezeForm.reason
      }

      try {
        const response = await request({
          url: '/buyerWallet/wallet/freezed',
          method: 'post',
          data: params
        })

        if (response.code === 200 || response.code === "200") {
         alert('冻结成功')
          this.freezeDialogVisible = false
          this.loadUserList()
        } else {
         alert(response.message)
         
        }
      } catch (error) {
        alert('网络错误：' + error.message)
      }
    },

    // 解冻钱包
    handleUnfreeze(user) {
      this.unfreezeUser = user
      this.unfreezeDialogVisible = true
    },

    // 提交解冻
    async confirmUnfreeze() {
      if (!this.unfreezeUser) return

      const params = {
        buyerUserId: this.unfreezeUser.buyerUserId,
        actionType: 1, // 1-解冻
        amount: 0,
        expireTime: ''
      }

      try {
        const response = await request({
          url: '/buyerWallet/wallet/freezed',
          method: 'post',
          data: params
        })

        if (response.code === 200 || response.code === "200") {
         alert('解冻成功')
          this.unfreezeDialogVisible = false
          this.loadUserList()
        } else {
          alert(response.message || '解冻失败')
              this.unfreezeDialogVisible = false
               this.loadUserList()
        }
      } catch (error) {
        alert('网络错误：' + error.message)
      }
    }
  },

  mounted() {
    this.loadUserList()
  }
}
</script>

<style scoped>
/* 样式保持不变，可复用原有样式 */
.user-manage-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.manage-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.manage-card .el-card__header {
  background-color: #409eff;
  color: white;
  border-radius: 8px 8px 0 0;
  padding: 15px 20px;
}

.search-section {
  margin-bottom: 20px;
  padding: 30px;
  background: white;
  border-radius: 6px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.user-list-section h3 {
  margin-bottom: 20px;
  color: #303133;
  font-size: 18px;
  font-weight: 600;
  border-bottom: 2px solid #409eff;
  padding-bottom: 10px;
}

.pagination-wrapper {
  text-align: center;
  margin-top: 20px;
  padding: 20px 0;
  background: white;
  border-radius: 6px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}
</style>